﻿using System;
using System.IO;
using System.Net.Http.Json;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;

class Program
{
    string publicKeyPath = "public.key";    // 公钥文件的路径
    string privateKeyPath = "private.key";  // 私钥文件的路径
    string plainData = "Server=127.0.0.1;Port=65532;Database=fedatabase;Uid=root;Pwd=root;";   // 待加密的明文数据
    string encryptedDataFilePath = "mysqlconnectionstring-local.bin";  // 保存密文的文档路径

    class User
    {
        public string? UserName { get; set; }
        public string? Password { get; set; }
    }

    static void Main()
    {

        //string certificate = "certificate.pfx";
        var app = new Program();

        app.Test();

        //var password = app.ConvertToEncryptedBase64String("admin");
        //var userName = "admin";

        //HttpClientHandler handler = new HttpClientHandler();

        //handler.ServerCertificateCustomValidationCallback = (a, b, c, d) => true;

        //handler.ClientCertificates.Add(new X509Certificate2(certificate, "LANXIAOFANG"));

        //HttpClient client = new HttpClient(handler);

        //var task = client.PostAsync("https://localhost:65530/Account/SignIn",
        //    JsonContent.Create(new User() { Password = password, UserName = userName }));

        //task.Wait();

        //Console.WriteLine(task.Result.ToString());

    }

    public void Test()
    {
        // 读取公钥文件
        string publicKey = File.ReadAllText(publicKeyPath);

        // 创建 RSA 实例，并加载公钥
        using (RSA rsa = RSA.Create())
        {
            rsa.ImportFromPem(publicKey);

            // 将明文数据转换为字节数组
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainData);

            // 使用公钥进行加密
            byte[] encryptedBytes = rsa.Encrypt(plainBytes, RSAEncryptionPadding.Pkcs1);

            // 将密文存储到文档
            File.WriteAllBytes(encryptedDataFilePath, encryptedBytes);

            // 输出保存密文的文档路径
            Console.WriteLine("Encrypted data saved to: " + encryptedDataFilePath);
        }

        // 读取私钥文件
        string privateKey = File.ReadAllText(privateKeyPath);

        // 创建 RSA 实例，并加载私钥
        using (RSA rsa = RSA.Create())
        {
            rsa.ImportFromPem(privateKey);

            // 读取密文数据
            byte[] encryptedBytes = File.ReadAllBytes(encryptedDataFilePath);

            // 使用私钥进行解密
            byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.Pkcs1);

            // 将解密后的字节数组转换为字符串
            string decryptedData = Encoding.UTF8.GetString(decryptedBytes);

            // 输出解密结果
            Console.WriteLine("Decrypted Data: " + decryptedData);
        }
    }

    /// <summary>
    /// 将明文进行加密，返回 Base64String 格式的加密字符串
    /// </summary>
    /// <param name="plainData">需要加密的明文</param>
    public string ConvertToEncryptedBase64String(string plainData)
    {
        if (string.IsNullOrWhiteSpace(File.ReadAllText(publicKeyPath)))
        {
            throw new InvalidOperationException("无效的 RSA 公钥，请检查系统公钥文件。");
        }

        // 创建 RSA 实例，并加载公钥
        using (RSA rsa = RSA.Create())
        {
            rsa.ImportFromPem(File.ReadAllText(publicKeyPath));

            // 将明文数据转换为字节数组
            byte[] plainBytes = Encoding.UTF8.GetBytes(plainData);

            // 使用公钥进行加密
            byte[] encryptedBytes = rsa.Encrypt(plainBytes, RSAEncryptionPadding.Pkcs1);

            // 转换为可读的 base64 字符串。
            var encryptedDataBase64 = Convert.ToBase64String(encryptedBytes);

            return encryptedDataBase64;
        }
    }

    /// <summary>
    /// 将 base64 加密字符串转换为明文字符串
    /// </summary>
    /// <param name="base64String"> base64 字符串</param>
    public string ConvertFromEncryptedBase64String(string base64String)
    {
        if (string.IsNullOrWhiteSpace(File.ReadAllText(privateKeyPath)))
        {
            throw new InvalidOperationException("无效的 RSA 私钥，请检查系统公钥文件。");
        }

        // 创建 RSA 实例，并加载私钥
        using (RSA rsa = RSA.Create())
        {
            rsa.ImportFromPem(File.ReadAllText(privateKeyPath));

            // 读取密文数据
            byte[] encryptedBytes = Convert.FromBase64String(base64String);

            // 使用私钥进行解密
            byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.Pkcs1);

            // 将解密后的字节数组转换为字符串
            string decryptedData = Encoding.UTF8.GetString(decryptedBytes);

            return decryptedData;
        }
    }
}
